package com.epam.web_project.bank.command.customer_commands;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Locale;
import java.util.ResourceBundle;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.epam.web_project.bank.command.Command;
import com.epam.web_project.bank.dao.account_dao.AccountDAO;
import com.epam.web_project.bank.dao.factory.MySQLDAOFactory;
import com.epam.web_project.bank.db.ConnectionPool;
import com.epam.web_project.bank.entity.Account;
import com.epam.web_project.bank.entity.Card;
import com.epam.web_project.bank.entity.Currency;
import com.epam.web_project.bank.entity.Customer;
import com.epam.web_project.bank.util.AppPropertiesLoader;
import com.epam.web_project.bank.util.CurrencyStringConverter;

public class CardRequestCommand implements Command {

	/*
	 * request a new card execute this from card_request.jspx used by regular
	 * customers and unapproved customers
	 */
	@Override
	public String execute(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String resPage;
		AppPropertiesLoader props = AppPropertiesLoader.getInstance();
		if("".equals(request.getParameter("limit"))) {
			return props.getProperty("show_card_request_command");
		}
		HttpSession session = request.getSession();
		Card card = new Card();
		card.setCardType(request.getParameter("card"));
		Account account = new Account();
		account.setCreditLimit(new BigDecimal(request.getParameter("limit")));
		Currency currency = CurrencyStringConverter.convertToCurrency(request
				.getParameter("currency"));
		account.setCurrency(currency); 
		account.setCard(card);
		Customer customer = (Customer) session.getAttribute("customer");
		if(customer==null) {
			return props.getProperty("login_page");
		}
		account.setOwnerId(customer.getId());
		MySQLDAOFactory daoFactory = new MySQLDAOFactory();
		daoFactory.setConnectionPool(ConnectionPool.getInstance());
		AccountDAO accountDAO = daoFactory.getAccountDAO();
		Locale locale=request.getLocale();
		ResourceBundle bundle=ResourceBundle.getBundle("i18n", locale);
		if (accountDAO.save(account)) {
			session.setAttribute("message",
					bundle.getString("java.card_req"));
			if (!customer.isOnApproval()) {
				resPage = props.getProperty("show_main_command");
			} else {
				resPage = props.getProperty("show_unnaproved_command");
			}
		} else {
			request.setAttribute("message",
					bundle.getString("java.card_req_fail"));
			resPage = props.getProperty("card_request_page");
		}
		return resPage;
	}

}
